<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="880px" @confirm="handleSubmit"
			@close="handleClose">
			<el-tabs v-model="lang" @tab-change="handChange">
				<el-tab-pane v-for="(item, index) in languages.list" :key="index" :label="item.name" :name="item.symbol"
					lazy></el-tab-pane>
			</el-tabs>
			<el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules" label-position="left">
				<div class="xl:flex">
					<div>
						<!-- <el-form-item label="质押类型" prop="type">
							<el-select class="flex-1" :disabled="formData.id!=''" v-model="formData.type" clearable placeholder="请选择质押类型">
								<el-option v-for="(item, index) in dictData.item_type" :key="index" :label="item.name"
									:value="parseInt(item.value)" />
							</el-select>
						</el-form-item> -->
						<el-form-item label="最小质押额" prop="min_money">
							<el-input type="number" v-model="formData.min_money" clearable placeholder="请输入最小质押额" />
						</el-form-item>
						<el-form-item label="最大质押额" prop="max_money">
							<el-input type="number" v-model="formData.max_money" clearable placeholder="请输入最大质押额" />
						</el-form-item>
						<el-form-item label="利率" prop="rate">
							<el-input type="number" v-model="formData.rate" clearable placeholder="请输入利率" />
						</el-form-item>
						<el-form-item label="周期" prop="cycle">
							<el-input type="number" v-model="formData.cycle" clearable placeholder="请输入周期" />
						</el-form-item>
						<el-form-item label="赠送积分" prop="point">
							<el-input type="number" v-model="formData.point" clearable placeholder="请输入赠送积分" />
						</el-form-item>
						<el-form-item label="限制等级" prop="member_id">
							<el-select class="flex-1" v-model="formData.member_id" placeholder="请选择会员等级" clearable>
								<el-option v-for="item in optionsData.members" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
						<el-form-item label="项目进度" prop="progress">
							<el-input type="number" v-model="formData.progress" clearable placeholder="请输入项目进度" />
						</el-form-item>
						<el-form-item label="自增进度" prop="progress_auto">
							<el-input type="number" v-model="formData.progress_auto" clearable placeholder="请输入自增进度" />
						</el-form-item>
						<el-form-item label="状态" prop="is_show">
							<el-radio-group v-model="formData.is_show">
								<el-radio :label="1">显示</el-radio>
								<el-radio :label="0">隐藏</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="排序" prop="sort">
							<div>
								<el-input-number type="number" v-model="formData.sort" :min="0" :max="9999" />
								<div class="form-tips">默认为0， 数值越大越排前</div>
							</div>
						</el-form-item>

					</div>
					<div class="xl:ml-20">
						<el-form-item label="项目标题" prop="title">
							<el-input v-model="formData.title" clearable placeholder="请输入项目标题" />
							<el-button type="primary" size="small" v-if="active!=0" @click="handTranslation('title')"
								:loading="loadingTran">翻译</el-button>
						</el-form-item>
						<el-form-item label="项目图片" prop="image">
							<material-picker v-model="formData.image" />
						</el-form-item>
						<el-form-item label="项目内容" prop="content">
							<editor class="flex-1" v-model="formData.content" :height="500" :width="375" />
						</el-form-item>
					</div>
				</div>
			</el-form>

		</popup>
	</div>
</template>

<script lang="ts" setup name="itemEdit">
	import type { FormInstance } from 'element-plus'
	import Popup from '@/components/popup/index.vue'
	import { useDictOptions } from '@/hooks/useDictOptions'
	import { apiItemAdd, apiItemEdit, apiItemDetail } from '@/api/item'
	import { translation } from '@/api/translation'
	import { apiLanguageAll } from '@/api/setting/language'
	import { apiUserMemberAll } from '@/api/user_member'
	import feedback from '@/utils/feedback'
	import type { PropType } from 'vue'
	defineProps({
		dictData: {
			type: Object as PropType<Record<string, any[]>>,
			default: () => ({})
		}
	})
	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')


	// 弹窗标题
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑项目' : '新增项目'
	})

	const languages = reactive({
		list: [{
			id: '',
			name: '',
			symbol: ''
		}],
		symbol: ''
	})

	const active = ref(0);
	const lang = ref("");
	const lang_1 = ref("");//切换前一个
	let langs = reactive([]);

	// 表单数据
	const formData = reactive({
		id: '',
		cid: 0,
		type: 1,
		title: '',
		image: '',
		content: '',
		min_money: 0,
		max_money: 99999999,
		rate: 0.1,
		cycle: 1,
		point:0,
		member_id:1,
		progress: 0,
		progress_auto: 0.01,
		is_show: 1,
		sort: 0,
		langs: []
	})


	// 表单验证
	const formRules = reactive<any>({
		type: [{
			required: true,
			message: '请选择质押类型',
			trigger: ['blur']
		}],
		title: [{
			required: true,
			message: '请输入项目标题',
			trigger: ['blur']
		}],
		min_money: [{
			required: true,
			message: '请输入最小质押额',
			trigger: ['blur']
		}],
		max_money: [{
			required: true,
			message: '请输入最大质押额',
			trigger: ['blur']
		}],
		rate: [{
			required: true,
			message: '请输入利率',
			trigger: ['blur']
		}],
		cycle: [{
			required: true,
			message: '请输入周期',
			trigger: ['blur']
		}],
		point: [{
			required: true,
			message: '请输入赠送积分',
			trigger: ['blur']
		}],
		member_id: [{
			required: true,
			message: '请选择会员等级',
			trigger: ['blur']
		}],
		progress: [{
			required: true,
			message: '请输入项目进度',
			trigger: ['blur']
		}],
		progress_auto: [{
			required: true,
			message: '请输入自增进度',
			trigger: ['blur']
		}],
		is_show: [{
			required: true,
			message: '请选择状态',
			trigger: ['blur']
		}]
	})


	// 获取详情
	const setFormData = async (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}
		langs = data['langs'];
	}

	const getDetail = async (row : Record<string, any>) => {
		const data = await apiItemDetail({
			id: row.id
		})
		setFormData(data)
	}
	
	const { optionsData } = useDictOptions<{
		members : any[]
	}>({
		members: {
			api: apiUserMemberAll
		}
	})

	// 提交按钮
	const handleSubmit = async () => {
		await formRef.value?.validate()
		//数组存储
		let arr = {
			'lang': lang.value,
			'title': formData.title,
			'image': formData.image,
			'content': formData.content,
		}

		//数组更新
		let array = pushArr(langs, lang.value, arr);
		langs = array;

		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if(langs[key]['title']!=""){
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})
		if(!exists) return feedback.msgError('首个语言必填');
		
		//输入初始化
		let arr2 = langs[langs_key];
		Object.keys(arr2).forEach((key) => {
			//@ts-ignore
			formData[key] = arr2[key]
		})

		formData.langs = langs;
		const data = { ...formData, }
		mode.value == 'edit'
			? await apiItemEdit(data)
			: await apiItemAdd(data)
		popupRef.value?.close()
		emit('success')
	}

	//打开弹窗
	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}

	// 关闭回调
	const handleClose = () => {
		emit('close')
	}

	const getData = async () => {
		const data = await apiLanguageAll()
		languages.list = data;
		languages.symbol = data[0]['symbol'];
		lang.value = languages.symbol;
	}
	//数组替换，存在替换，不存在追加
	const pushArr = (arr : any, lang : string, params : any) => {
		let result = false;
		Object.keys(arr).forEach((key) => {
			if (arr[key]['lang'] == lang) {
				arr[key] = params;
				result = true;
			}
		})

		if (!result) {
			arr.push(params);
		}
		return arr;
	}
	//标签切换
	const handChange = async (data : string) => {
		let lang_last = lang_1.value;
		lang_1.value = data
		const index = languages.list.findIndex((item) => item.symbol === data);
		active.value = index;

		//数组存储
		if (lang_last != "") {
			let arr = {
				'lang': lang_last,
				'title': formData.title,
				'image': formData.image,
				'content': formData.content,
			}
			let array = pushArr(langs, lang_last, arr);
			langs = array;
		}
		//输入初始化
		let arr2 = {
			'lang': "",
			'title': "",
			'image': "",
			'content': "",
		}
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == data) {
				arr2 = langs[key];
			}
		})

		if (lang_last != "") {
			Object.keys(arr2).forEach((key) => {
				//@ts-ignore
				formData[key] = arr2[key]
			})
		}
		
		if (localStorage.getItem('trans_auto') == '1' && formData.title == '' && active.value != 0) {
			handTranslation('title')
		}
	}
	
	//翻译
	const loadingTran = ref(false);
	const handTranslation = async (field : string) => {
	
		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;
	
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if (langs[key][field] != "") {
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})
		if (!exists) return feedback.msgError('首个语言必填');
		const qArray = [langs[langs_key][field]]
	
		if (qArray.length > 0) {
			loadingTran.value = true;
			const res = await translation({
				qArray: qArray,
				from: languages.list[0]['trans_symbol'],
				to: languages.list[active.value]['trans_symbol']
			})
			formData[field] = res['result'][0]['translation'];
			loadingTran.value = false;
		}
	
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
	getData()
</script>